<?php


namespace App\Imports;

use App\Services\BaseService;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithColumnLimit;
use Maatwebsite\Excel\Concerns\WithStartRow;
use PHPUnit\Util\Exception;

/**
 * Class BookCatalogImportA
 * @package App\Imports
 * 下面发现个现象 BookCatalogImportA 如果 implements  SkipsEmptyRows会导致  WithStartRow 失效
 */
class PhotoCatalogImport implements ToModel, WithStartRow, WithColumnLimit
{
    protected $partCompanyId;
    protected $startRow;
    protected $redisExpireTime;
    protected $stop;
    protected $photoArchiveInstance;
    protected $photoCatalogInstance;
    protected $archivesNoKey;
    protected $photoArchiveIdKey;

    /**
     * 如果一个档案号 10 秒内出现多次，直接视为一个档案号多页写入数据，不进行覆盖
     */
    public function __construct($partCompanyId, $photoClassifyId, $importCountKey)
    {
        $this->importCountKey       = $importCountKey;
        $this->stop                 = 0; //0继续读取，1停止读取
        $this->startRow             = 2; //从第几行开始
        $this->photoArchiveIdKey    = 'photo_archives_id:' . $importCountKey;
        $this->archivesNoKey        = 'archives_no:' . $importCountKey;
        $this->redisExpireTime      = 10; //把档案号存起来，如果10秒内出现重复的档案号，直接认为是追加数据，而不是覆盖
        $this->partCompanyId        = request()->input('part_company_id');
        $this->photoClassifyId      = request()->input('photo_classify_id');
        $this->photoArchiveInstance = (new BaseService())->getPhotoArchiveInstance($partCompanyId, $photoClassifyId);
        $this->photoCatalogInstance = (new BaseService())->getPhotoCatalogInstance($partCompanyId, $photoClassifyId);
    }

    /**
     * 注意：self::cacheBookTitleId($archivesNo); 不可以从 if ...else... 里面拿出来合为一个！
     */
    public function model(array $row)
    {
        if (!(empty($row[0]) && empty($row[1]))) { //不同时为空，就视为有数据
            if ($row[0] == 'ee') $this->stop = 1; //如果出现了指定【终止标识】，不在写入
            if (str_contains(trim($row[0]), '档案号：')) { //第一种格式：有档案号
                $archivesNo = mb_substr(trim($row[0]), 4);
                $archivesNo = format_archives_no($archivesNo);
                self::cacheBookTitleId($archivesNo);
            }
            $archivesNo = redis()->get($this->archivesNoKey);
            if (!empty($archivesNo)) {
                $photoArchiveId = redis()->get($this->photoArchiveIdKey);
                if (empty($photoArchiveId)) {
                    throw new Exception("找不到档案号 {$row[0]}！格式存在错误");
                }
                if (!$this->stop && is_numeric($row[0])) { //只写入序号为数字的例如 1、2、3....
                    redis()->incr($this->importCountKey); //导入的数据量加
                    $this->photoCatalogInstance->insert([
                        'photo_archives_id' => $photoArchiveId,
                        'serial_no'         => format_str($row[0]), //照片号
                        'title'             => format_str($row[1]), //照片题名
                        'photo_date'        => format_str($row[2]), //拍摄日期
                        'page_num'          => to_int($row[3]),     //页次
                        'negative_no'       => format_str($row[4]), //底片号
                        'remark'            => format_str($row[5]), //备注
                        'photo_user'        => format_str($row[6]), //拍摄者
                        'created_at'        => now(),
                        'updated_at'        => now(),
                        "creator_id"        => user_id(),
                    ]);
                }
            }
        }
    }

    /**
     * 使用档案号查询案卷目录id，查出后进行缓存
     */
    private function cacheBookTitleId($archivesNo)
    {
        if ($archivesNo && (redis()->get($this->archivesNoKey) != $archivesNo)) { //如果10秒内档案号一致，继续写入，不覆盖
            $photoArchiveId = $this->photoArchiveInstance->where('archives_no', $archivesNo)->value('id');
            if (empty($photoArchiveId)) {
                throw new Exception('找不到档案号：' . $archivesNo . ',是否有隐藏的sheet表格？请尝试新建个xlsx文件,并复制所需数据');
            }
            redis()->setex($this->archivesNoKey, $this->redisExpireTime, $archivesNo); //把档案号存起来
            redis()->setex($this->photoArchiveIdKey, $this->redisExpireTime, $photoArchiveId); //暂存案卷目录id
            $this->photoArchiveInstance->where('id', $photoArchiveId)->update(['is_have_data' => 1, 'is_need_check' => 1]); //更新为没有数据,需要检查
            $this->photoCatalogInstance->where('photo_archives_id', $photoArchiveId)->delete();
        }
    }

    /**
     * 直接过滤表头，第一块数据含表头
     *
     * @return int
     */
    public function startRow(): int
    {
        return $this->startRow;
    }

    /**
     * @return string
     * @author: lxk
     * @date: 2023/9/12 17:23
     */
    public function endColumn(): string
    {
        return 'G';
    }


}
